<?php

namespace App\Http\Controllers;

use App\Models\Config;
use Illuminate\Support\Facades\Storage;
use Yo;
use Login;

class ConfigController extends Controller
{
    public function config()
    {
        $configs = $this->get_config_list([1, 2, 3, 4]);
        $list = [];
        foreach ($configs as $config) {
            $list[$config['mark']] = $config['value'];
        }
        return Yo::echo($list);
    }

    public function update()
    {
        Login::admin(9);
        $mark = request()->get('mark');
        $value = request()->get('value');
        $config = Config::where('mark', $mark)->first();
        if (!$config) Yo::error_echo(100008);
        switch ($mark) {
            case 'logo':
            case 'favicon':
            case 'login_image':
                $base64 = $value;
                if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
                    $type = ['png', 'jpeg', 'jpg', 'gif'];
                    if (!in_array($result[2], $type)) Yo::error_echo(100019);
                    $disk = Storage::disk('public');
                    $path = "/assets/$mark.$result[2]";
                    $put = $disk->put($path, base64_decode(str_replace($result[1], '', $base64)));
                    if (!$put) Yo::error_echo(100020);
                    $save = "/storage/assets/$mark.$result[2]?t=" . time();
                } else {
                    Yo::error_echo(100020);
                }
                break;
            default:
                $save = $value;
        }
        $config->value = $save;
        $config->save();
        return Yo::update_echo($config->id);
    }

    public function assets_list()
    {
        Login::admin(9);
        $configs = $this->get_config_list([1, 2, 3, 4]);
        $list = [];
        foreach ($configs as $config) {
            $list[$config['mark']] = $config['value'];
        }
        return Yo::echo($list);
    }

    public function get_config_list($arr)
    {
        return Config::whereIn('id', $arr)->get();
    }
}
